from django import http
from django.http import JsonResponse
from django.shortcuts import render

from apps.verifications import constants
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
# Create your views here.
from django.views import View

from utils.response_code import RETCODE
# from multiprocessing.dummy import Pool
# pool = Pool()
# pool.apply_async()
class SmsCodeView(View):
    def get(self,request,mobile):
        #1.接收３个ｍｏｂile，图片验证码img_code;uuid == image_code_id
        image_code = request.GET.get('image_code')
        uuid = request.GET.get("image_code_id")
        # *2.验证码　img_code和redis存储的验证码　是否一致　（１.redis取出来（４步）２．判断是否相等３．ｒｅdis ）
        #2.1链接redis
        img_redis_client = get_redis_connection("verify_image_code")
        #2.2取出来uuid
        redis_img_code = img_redis_client.get("img_%s"% uuid)
        if redis_img_code is None:
            return http.JsonResponse({"code":"4001","errmsg":"验证码失效了"})
        #２．３判断
        # 千万注意　　redis 取出来类型是　Bytes.decode()
        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'code':"4001",'errmsg':'输入图形验证码有误'})
        # 2.4删除　　redis里面　image_code
        img_redis_client.delete("img_%s"%uuid)
        # 生成随机　６位　短信验证码内容
        from random import randint
        sms_code ="%06d"%randint(0,999999)
        # 4存储　　随机６位　　redis里面（３步）
        sms_redis_client = get_redis_connection("sms_code")
        #1.从redis中取出　避免频繁发短信
        send_flag = sms_redis_client.get("send_flag_%s"%mobile)
        #2.判断　　如果标识存在，不能再次发送
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR,"errmsg":"发送短信过于频繁"})
        p1 = sms_redis_client.pipeline()
        p1.setex("send_flag_%s"%mobile,60,1)
        p1.setex("sms_%s" % mobile,constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)
        p1.execute()
        # 5.发短信－－－第三方容联云
        from celery_tasks.sms.tasks import cpp_send_sms_code
        cpp_send_sms_code.delay(mobile,sms_code)





        sms_redis_client.setex("sms_%s"%mobile,constants.IMAGE_CODE_REDIS_EXPIRES,sms_code)
        # 发短信－－－第三方容联云
        # from libs.yuntongxun.sms import CCP
        # # 手机号　　验证码　　过期时间　　短信模板１
        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_EXPIRES],1)
        print("短信验证码是：",sms_code)
        # 6.返回响应对象
        return http.JsonResponse({"code":"0","errmsg":"发送短信成功"})
        pass

















class ImageCodeView(View):
    def get(self,request,uuid):
        text,image_code = captcha.generate_captcha()
        img_redis_client = get_redis_connection("verify_image_code")
        from . import constants
        img_redis_client.setex("img_%s"%uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        # 4.返回给前端　图片的二进制 111
        return http.HttpResponse(image_code,content_type="image/jpeg")

